package com.example.linearlayoutdemo.network.auth.auth;

import android.util.Log;

import com.example.linearlayoutdemo.network.auth.model.LoginResponse;
import com.example.linearlayoutdemo.network.auth.model.RegisterResponse;
import com.example.linearlayoutdemo.network.auth.model.User;
import com.example.linearlayoutdemo.network.auth.utils.ThreadManager;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * API服务类，处理所有网络请求
 */
public class ApiService {
    private static final String TAG = "ApiService";
    private static final String BASE_URL = "https://reqres.in/api/";
    private static final int CONNECT_TIMEOUT = 5000;
    private static final int READ_TIMEOUT = 5000;

    private static volatile ApiService instance;
    private final Gson gson;
    private final ThreadManager threadManager;

    private ApiService() {
        gson = new Gson();
        threadManager = ThreadManager.getInstance();
    }

    public static ApiService getInstance() {
        if (instance == null) {
            synchronized (ApiService.class) {
                if (instance == null) {
                    instance = new ApiService();
                }
            }
        }
        return instance;
    }

    /**
     * 登录请求
     */
    public void login(User user, ApiCallback<LoginResponse> callback) {
        threadManager.runOnMainThread(callback::onStart);

        threadManager.executeNetworkTask(() -> {
            HttpURLConnection connection = null;
            InputStream inputStream = null;

            try {
                URL url = new URL(BASE_URL + "login");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(CONNECT_TIMEOUT);
                connection.setReadTimeout(READ_TIMEOUT);
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                connection.setRequestProperty("x-api-key", "reqres-free-v1");

                // 发送请求体
                String jsonInputString = gson.toJson(user);
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                // 处理响应
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inputStream = connection.getInputStream();
                    String response = readStream(inputStream);
                    LoginResponse loginResponse = gson.fromJson(response, LoginResponse.class);
                    if(loginResponse.getToken() != null) {
                        User user2 = new User(user.getUsername(),user.getPassword(),user.getEmail());
                        user2.setToken(loginResponse.getToken());
                        loginResponse.setUser(user2);
                        loginResponse.setSuccess(true);
                    }

                    threadManager.runOnMainThread(() -> {
                        callback.onSuccess(loginResponse);
                        callback.onComplete();
                    });
                } else {
                    String errorMsg = "登录失败，响应码: " + responseCode;
                    Log.e(TAG, errorMsg);
                    threadManager.runOnMainThread(() -> {
                        callback.onFailure(new Exception(errorMsg));
                        callback.onComplete();
                    });
                }
            } catch (Exception e) {
                Log.e(TAG, "登录异常", e);
                threadManager.runOnMainThread(() -> {
                    callback.onFailure(e);
                    callback.onComplete();
                });
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        Log.e(TAG, "关闭输入流失败", e);
                    }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
        });
    }

    /**
     * 注册请求
     */
    public void register(User user, ApiCallback<RegisterResponse> callback) {
        threadManager.runOnMainThread(callback::onStart);

        threadManager.executeNetworkTask(() -> {
            HttpURLConnection connection = null;
            InputStream inputStream = null;

            try {
                URL url = new URL(BASE_URL + "register");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(CONNECT_TIMEOUT);
                connection.setReadTimeout(READ_TIMEOUT);
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                connection.setRequestProperty("x-api-key", "reqres-free-v1");

                // 发送请求体
                String jsonInputString = gson.toJson(user);
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                // 处理响应
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inputStream = connection.getInputStream();
                    String response = readStream(inputStream);
                    RegisterResponse registerResponse = gson.fromJson(response, RegisterResponse.class);

                    threadManager.runOnMainThread(() -> {
                        callback.onSuccess(registerResponse);
                        callback.onComplete();
                    });
                } else {
                    String errorMsg = "注册失败，响应码: " + responseCode;
                    Log.e(TAG, errorMsg);
                    threadManager.runOnMainThread(() -> {
                        callback.onFailure(new Exception(errorMsg));
                        callback.onComplete();
                    });
                }
            } catch (Exception e) {
                Log.e(TAG, "注册异常", e);
                threadManager.runOnMainThread(() -> {
                    callback.onFailure(e);
                    callback.onComplete();
                });
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        Log.e(TAG, "关闭输入流失败", e);
                    }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
        });
    }

    /**
     * 自动登录请求
     */
    public void autoLogin(String token, ApiCallback<LoginResponse> callback) {
        threadManager.runOnMainThread(callback::onStart);

        threadManager.executeNetworkTask(() -> {
            HttpURLConnection connection = null;
            InputStream inputStream = null;

            try {
                URL url = new URL(BASE_URL + "auto-login");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(CONNECT_TIMEOUT);
                connection.setReadTimeout(READ_TIMEOUT);
                // 添加Token到请求头
                connection.setRequestProperty("Authorization", "Bearer " + token);
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

                // 处理响应
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inputStream = connection.getInputStream();
                    String response = readStream(inputStream);
                    LoginResponse loginResponse = gson.fromJson(response, LoginResponse.class);

                    threadManager.runOnMainThread(() -> {
                        callback.onSuccess(loginResponse);
                        callback.onComplete();
                    });
                } else {
                    String errorMsg = "自动登录失败，响应码: " + responseCode;
                    Log.e(TAG, errorMsg);
                    threadManager.runOnMainThread(() -> {
                        callback.onFailure(new Exception(errorMsg));
                        callback.onComplete();
                    });
                }
            } catch (Exception e) {
                Log.e(TAG, "自动登录异常", e);
                threadManager.runOnMainThread(() -> {
                    callback.onFailure(e);
                    callback.onComplete();
                });
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        Log.e(TAG, "关闭输入流失败", e);
                    }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
        });
    }

    /**
     * 将输入流转换为字符串
     */
    private String readStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        reader.close();
        return stringBuilder.toString();
    }

    /**
     * 网络请求回调接口
     */
    public interface ApiCallback<T> {
        void onStart();
        void onSuccess(T response);
        void onFailure(Exception e);
        void onComplete();
    }
}

